//
//  ZHZLearnCtry.m
//  ZHZtest
//
//  Created by 李彦宏 on 2017/12/12.
//  Copyright © 2017年 LYH. All rights reserved.
//
#define kViolet [UIColor colorWithRed:170/255.0 green:114/255.0 blue:219/255.0 alpha:1.0]
#define themeColor  [UIColor colorWithRed:235/255.0f green:91/255.0f blue:87/255.0f alpha:1]
//按钮view背景213，213，213

#import "ZHZLearnCtry.h"
#import "FSCalendar.h"
#import "QFTimePickerView.h"
#import "BRPickerView.h"
#import "LZPickViewManager.h"
@interface ZHZLearnCtry ()<FSCalendarDataSource,FSCalendarDelegate,FSCalendarDelegateAppearance>
@property (weak, nonatomic) FSCalendar *calendar;
@property (strong, nonatomic) NSDateFormatter *dateFormatter;
@property (strong, nonatomic) NSDictionary *fillDefaultColors;
@property (strong, nonatomic) UIButton *startTimeBtn;
@property (strong, nonatomic) UIButton *endTimeBtn;
@property (strong, nonatomic) UIButton *chooseStuBtn;
@property (strong, nonatomic) NSString *yDate;
@property (strong, nonatomic) NSString *sid;
@end

@implementation ZHZLearnCtry
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.dateFormatter = [[NSDateFormatter alloc] init];
        self.dateFormatter.dateFormat = @"yyyyMMdd";
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self ChooseStudent];
    [self SendLessonUI];
    [self ChooseTimeUI];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.calendar.accessibilityIdentifier = @"calendar";
    self.yDate = [self.dateFormatter stringFromDate:[NSDate date]];
    
}
-(void)viewWillAppear:(BOOL)animated{
        [super viewWillAppear:animated];
    [self.endTimeBtn setTitle:@"结束时间" forState:UIControlStateNormal];
    [self.startTimeBtn setTitle:@"开始时间" forState:UIControlStateNormal];
    [self.chooseStuBtn setTitle:@"点击选择" forState:UIControlStateNormal];
}
- (void)loadView
{
    UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.view = view;
    //日历的背景
    UIImageView *calendarBack = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"日历"]];
    calendarBack.frame = CGRectMake(20, Navigation_Bar_Height+10, ScreenWidth-40,ScreenHeight/2+10);
    [self.view addSubview:calendarBack];
    FSCalendar *calendar = [[FSCalendar alloc] initWithFrame:CGRectMake(25, Navigation_Bar_Height+15, ScreenWidth-50, ScreenHeight/2)];
    calendar.dataSource = self;
    calendar.delegate = self;
    //允许多选,可以选中多个日期
    calendar.allowsMultipleSelection = NO;
    calendar.swipeToChooseGesture.enabled = YES;
    calendar.placeholderType = FSCalendarPlaceholderTypeNone;
    calendar.backgroundColor = [UIColor clearColor];
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];//设置为中文
    calendar.locale = locale;  // 设置周次是中文显示
    calendar.appearance.caseOptions = FSCalendarCaseOptionsWeekdayUsesSingleUpperCase|FSCalendarCaseOptionsHeaderUsesUpperCase;;//中文
    calendar.appearance.headerDateFormat = @"yyyy年MM月";
    calendar.appearance.borderRadius = 1;//圆形
    //设置字体大小\颜色
    calendar.appearance.subtitleFont = [UIFont systemFontOfSize:8];
    calendar.appearance.headerTitleColor = [UIColor whiteColor];
    calendar.appearance.weekdayTextColor = [UIColor whiteColor];
    calendar.appearance.selectionColor = [UIColor orangeColor];
    //日历头部颜色
    calendar.calendarHeaderView.backgroundColor = themeColor;
    calendar.calendarWeekdayView.backgroundColor = themeColor;
    //隐藏上下月的透明度
    calendar.appearance.headerMinimumDissolvedAlpha = 0;
    [self.view addSubview:calendar];
    self.calendar = calendar;
    //    UIBarButtonItem *todayItem = [[UIBarButtonItem alloc] initWithTitle:@"今天" style:UIBarButtonItemStylePlain target:self action:@selector(todayItemClicked:)];
    //    self.navigationItem.rightBarButtonItem = todayItem;
}

-(void)ChooseTimeUI{
    UIView *backview1=[[UIView alloc]initWithFrame:CGRectMake(20,(Navigation_Bar_Height+10+(ScreenHeight/2+10))+10, ScreenWidth-50, 50)];
    backview1.backgroundColor = [UIColor clearColor];
    UILabel *chooseleb=[[UILabel alloc]initWithFrame:CGRectMake(8, 10, 140, 30)];
    chooseleb.text=@"上课时间:";
    chooseleb.textAlignment=NSTextAlignmentLeft;
    chooseleb.textColor=[UIColor blackColor];
    chooseleb.font=[UIFont systemFontOfSize:16];
    
    UIButton *startTime=[[UIButton alloc]initWithFrame:CGRectMake(80, 10,80, 30)];
    [startTime setTitle:@"开始时间" forState:UIControlStateNormal];
    startTime.tag = 1;
    [startTime setBackgroundColor:dominantColor];
    [startTime setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    startTime.titleLabel.font=[UIFont systemFontOfSize:14];
    [startTime addTarget:self action:@selector(sendBtnAction:) forControlEvents:UIControlEventTouchDown];
    self.startTimeBtn = startTime;
    
    UIButton *endTime=[[UIButton alloc]initWithFrame:CGRectMake(160, 10,80, 30)];
    [endTime setTitle:@"结束时间" forState:UIControlStateNormal];
    endTime.tag = 2;
    [endTime setBackgroundColor:dominantColor];
    [endTime setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    endTime.titleLabel.font=[UIFont systemFontOfSize:14];
    [endTime addTarget:self action:@selector(sendBtnAction:) forControlEvents:UIControlEventTouchDown];
    self.endTimeBtn = endTime;
    
    [backview1 addSubview:chooseleb];
    [backview1 addSubview:startTime];
    [backview1 addSubview:endTime];
    [self.view addSubview:backview1];
}

-(void)ChooseStudent{
    UIView *backview1=[[UIView alloc]initWithFrame:CGRectMake(20,(Navigation_Bar_Height+10+(ScreenHeight/2+10))+10+35, ScreenWidth-50, 50)];
    backview1.backgroundColor = [UIColor clearColor];
    UILabel *chooseleb=[[UILabel alloc]initWithFrame:CGRectMake(8, 10, 140, 30)];
    chooseleb.text=@"选择学生:";
    chooseleb.textAlignment=NSTextAlignmentLeft;
    chooseleb.textColor=[UIColor blackColor];
    chooseleb.font=[UIFont systemFontOfSize:16];
    
    UIButton *chooseStu=[[UIButton alloc]initWithFrame:CGRectMake((ScreenWidth-200)/2, 10,200, 30)];
    [chooseStu setTitle:@"点击选择" forState:UIControlStateNormal];
    chooseStu.tag = 4;
    chooseStu.layer.cornerRadius = 5;
    [chooseStu setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    chooseStu.titleLabel.font=[UIFont systemFontOfSize:14];
    [chooseStu addTarget:self action:@selector(sendBtnAction:) forControlEvents:UIControlEventTouchDown];
    self.chooseStuBtn = chooseStu;
    
    [backview1 addSubview:chooseleb];
    [backview1 addSubview:chooseStu];
    [self.view addSubview:backview1];
}
-(void)SendLessonUI{
    //发送约课按钮背景View
    UIView *backview=[[UIView alloc]initWithFrame:CGRectMake(20, (Navigation_Bar_Height+10+(ScreenHeight/2+10))+10+60+20, ScreenWidth-50, 50)];
    backview.backgroundColor = [UIColor clearColor];
    UIButton *sendBtn=[[UIButton alloc]initWithFrame:CGRectMake(40, 10, ScreenWidth-130, 30)];
    sendBtn.tag = 3;
    [sendBtn setTitle:@"发送约课" forState:UIControlStateNormal];
    [sendBtn setBackgroundColor:dominantColor];
    [sendBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    sendBtn.titleLabel.font=[UIFont systemFontOfSize:17];
    //设置圆角
    sendBtn.layer.cornerRadius=5;
    [sendBtn addTarget:self action:@selector(sendBtnAction:) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:backview];
    [backview addSubview:sendBtn];
}
- (void)dealloc
{
    NSLog(@"%s",__FUNCTION__);
}
#pragma mark - 发送约课
-(void)sendBtnAction:(UIButton *)sender{
    switch (sender.tag) {
        case 1:
        { NSLog(@"开始时间");
            QFTimePickerView *pickerView = [[QFTimePickerView alloc]initDatePackerWithStartHour:@"08" endHour:@"23" period:15 response:^(NSString *str) {
                [self.startTimeBtn setTitle:str forState:UIControlStateNormal];
            }];
            [pickerView show];
            
        }
            break;
        case 2:
        { NSLog(@"结束时间");
            QFTimePickerView *pickerView = [[QFTimePickerView alloc]initDatePackerWithStartHour:@"08" endHour:@"23" period:15 response:^(NSString *str) {
                [self.endTimeBtn setTitle:str forState:UIControlStateNormal];
            }];
            [pickerView show];
        }
            break;
        case 3:
        {
            if ([self.startTimeBtn.titleLabel.text isEqualToString:@"开始时间"]) {
                // [Utility showFail:@"请选择开始时间"];
            }else{
                if ([self.endTimeBtn.titleLabel.text isEqualToString:@"结束时间"]){
                    // [Utility showFail:@"请选择结束时间"];
                }else{
                    if (self.sid !=nil) {
                        [self sendData];
                    }else{
                        [Utility showFail:@"请选择学生"];
                    }
                    
                }
            }
        }
            break;
        case 4:
        {
            [self requestStudentList];
        }
            break;
        default:
            break;
    }
}
#pragma mark - 请求学生列表
-(void)requestStudentList{
    
    NSDictionary *dict = @{
                           @"gid" : Gid,
                           @"gpass" : Gpassword                           };
    
    [[AFNetworkTool shareManager]postJSONWithUrl:Student_List parmas:dict successData:^(id json) {
        NSDictionary * resuts = json;
        if ([resuts[@"message"] isEqualToString:@"success"]) {
            NSArray *listArr = json[@"data"];
            if (listArr.count>0) {
                [self showStudentWithArray:listArr];
            }else{
                [Utility showFail:@"您还没分配学生,请联系教务老师!"];
            }
            
        }
    } failure:^(NSError *error) {
        
    }];
    NSLog(@"选择学生");
}
/*
 * 显示pickview
 * array  不使用model数组 直接用接口返回的数组数据
 * LZPickViewManager 中有定义的方法的注释 自己。
 */
- (void)showStudentWithArray:(NSArray *)array{
    //是不是你要的对
    LZPickViewManager  * manager = [LZPickViewManager initLZPickerViewManager];
    
    [manager setPickViewTopWithLeftButtonColor:[UIColor darkGrayColor] withRightButtonColor:[UIColor redColor] withTitleColor:[UIColor darkGrayColor] withTopBgColor:[UIColor whiteColor]];
    [manager setMultiPickerViewComponentOneShowKeyName:@"name" withBackKeyName:@"id"];
    
    [manager showMultiPickerViewWithData:array withComponentCount:1 withCompltedBlock:^(NSString *componentOneShow, NSString *componentOneBack, NSString *componentTwoShow, NSString *componentTwoBack, NSString *componentThreeShow, NSString *componentThreeBack) {
        [self.chooseStuBtn setTitle:componentOneShow forState:UIControlStateNormal];
        self.sid = componentOneBack;
        
    } cancelBlock:^{
        
    }];
}
#pragma mark - 发送约课
-(void)sendData{
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
    
    NSString *startTime = [NSString stringWithFormat:@"%@  %@",self.yDate,self.startTimeBtn.titleLabel.text];
    NSString *endTime = [NSString stringWithFormat:@"%@  %@",self.yDate,self.endTimeBtn.titleLabel.text];
    NSString * start = [self getTimeStrWithString:startTime];
    NSString * end = [self getTimeStrWithString:endTime];
    //转成doubleValue数值比较
    if ([start doubleValue] <[end doubleValue]) {
        if ([start doubleValue] > [timeString doubleValue]) {
            NSDictionary *dict = @{
                                   @"gid" : Gid,
                                   @"gpass" : Gpassword,
                                   @"starttime":start,
                                   @"endtime":end,
                                   @"datetime":self.yDate,
                                   @"sid" : self.sid
                                   };
            [[AFNetworkTool shareManager]postJSONWithUrl:Graduate_Order parmas:dict successData:^(id json) {
                // NSLog(@">>>>>>%@", json);
                [Utility showSuccess:json[@"message"]];
            } failure:^(NSError *error) {
                // NSLog(@"%@",error);
                [Utility showFail:@"网络错误"];
            }];
        }else{
            [Utility showFail:@"当前时间大于约课时间"];
        }
        
    }else{
        [Utility showFail:@"开始时间必须小于结束时间"];
    }
}
#pragma mark - Target actions

- (void)todayItemClicked:(id)sender
{
    [_calendar setCurrentPage:[NSDate date] animated:NO];
    _calendar.appearance.todayColor = [UIColor redColor];
    _calendar.appearance.titleTodayColor = [UIColor whiteColor];
    
}

#pragma mark - <FSCalendarDataSource>

- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition
{
    self.yDate = [self.dateFormatter stringFromDate:date];
    _calendar.appearance.todayColor = [UIColor clearColor];
    _calendar.appearance.titleTodayColor = [UIColor darkTextColor];
}

//设置最小日期

- (NSDate *)minimumDateForCalendar:(FSCalendar *)calendar

{
    
    return [NSDate date];
    
}

//最大

- (NSDate *)maximumDateForCalendar:(FSCalendar *)calendar

{
    NSCalendar *calender = [NSCalendar currentCalendar];
    // 设置属性，因为我只需要年,月,日，这个属性还可以支持时，分，秒
    NSDateComponents *cmp = [calender components:(NSCalendarUnitMonth | NSCalendarUnitYear|NSCalendarUnitDay) fromDate:[[NSDate alloc] init]];
    //设置上个月，即在现有的基础上减去一个月(2017年1月 减去一个月 会得到2016年12月)
    // [cmp setMonth:[cmp month] + 1];
    [cmp setDay:[cmp day] + 30];
    //拿到上个月的NSDate，再用NSDateFormatter就可以拿到单独的年和月了。
    NSDate *lastMonDate = [calender dateFromComponents:cmp];
    return lastMonDate;
    
}

- (NSString *)getTimeStrWithString:(NSString *)str{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象
    [dateFormatter setDateFormat:@"yyyyMMdd HH:mm"]; //设定时间的格式
    NSDate *tempDate = [dateFormatter dateFromString:str];//将字符串转换为时间对象
    NSString *timeStr = [NSString stringWithFormat:@"%ld", (long)[tempDate timeIntervalSince1970]];//字符串转成时间戳
    return timeStr;
}
// 时间戳转时间,时间戳为13位是精确到毫秒的，10位精确到秒
- (NSString *)getDateStringWithTimeStr:(NSString *)str{
    NSTimeInterval time=[str doubleValue];//传入的时间戳str如果是精确到毫秒的记得要/1000
    NSDate *detailDate=[NSDate dateWithTimeIntervalSince1970:time];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; //实例化一个NSDateFormatter对象
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *currentDateStr = [dateFormatter stringFromDate: detailDate];
    return currentDateStr;
}
#pragma mark - <FSCalendarDelegateAppearance>


- (UIColor *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance fillDefaultColorForDate:(NSDate *)date
{
    NSString *key = [self.dateFormatter stringFromDate:date];
    if ([_fillDefaultColors.allKeys containsObject:key]) {
        return _fillDefaultColors[key];
    }
    return nil;
}
@end

